package com.ylq.reggie_take_away.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylq.reggie_take_away.common.R;
import com.ylq.reggie_take_away.dto.SetMealDto;
import com.ylq.reggie_take_away.entity.Category;
import com.ylq.reggie_take_away.entity.SetMeal;
import com.ylq.reggie_take_away.service.CategoryService;
import com.ylq.reggie_take_away.service.SetMealDishService;
import com.ylq.reggie_take_away.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetMealController {

    @Autowired
    private SetMealService setMealService;

    @Autowired
    private SetMealDishService setMealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增套餐
     * @param setMealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true) //清理这个分类下所有缓存数据
    public R<String> save(@RequestBody SetMealDto setMealDto) {
        log.info("套餐信息：{}", setMealDto);
        setMealService.saveWithDish(setMealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 查询套餐，dto作用：把查到的套餐信息字段中的套餐分类（数据库中存的是另一张表category的id）
     * 根据id查询出名称来然后添加到dto返回前端
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<SetMeal> pageInfo = new Page<>(page, pageSize);
        //数据展示优化
        Page<SetMealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<SetMeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, SetMeal::getName, name);
        //根据更新时间降序排列
        queryWrapper.orderByDesc(SetMeal::getUpdateTime);
        setMealService.page(pageInfo, queryWrapper);

        //records就是数据，拷贝的时候因为泛型不一样所以要忽略它，并重新设置
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<SetMeal> records = pageInfo.getRecords();
        List<SetMealDto> list = records.stream().map((item) -> {
            SetMealDto setMealDto = new SetMealDto();
            BeanUtils.copyProperties(item, setMealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象, 获取分类名称
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                setMealDto.setCategoryName(categoryName);
            }
            return setMealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 删除套餐，删除两张表的数据，套餐和菜品关系
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true) //清理这个分类下所有缓存数据
    public R<String> delete(@RequestParam List<Long> ids) {
        setMealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status,@RequestParam Long ids) {
        // 根据ids查询对应的套餐记录
        LambdaQueryWrapper<SetMeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetMeal::getId, ids);
        SetMeal setMeal = setMealService.getOne(queryWrapper);
        if (setMeal == null) {
            return R.error("未找到对应的套餐记录");
        }
        // 根据传入的status决定要设置的新状态
        int newStatus;
        if (setMeal.getStatus() == 0) {
            newStatus = 1;
        } else {
            newStatus = 0;
        }
        // 设置新的状态值并更新到数据库
        setMeal.setStatus(newStatus);
        /**
         * 这个方法不用在service写，直接调用service层继承的updateById方法就能实现
         */
        setMealService.updateStatus(setMeal);

        return R.success("修改成功");
    }

    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<SetMeal>> list(SetMeal setmeal){
        LambdaQueryWrapper<SetMeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,SetMeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,SetMeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(SetMeal::getUpdateTime);

        List<SetMeal> list = setMealService.list(queryWrapper);

        return R.success(list);
    }


}
